<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/static/layui/css/layui.css?t=1" type="text/css" media="screen" />
    <link rel="stylesheet" href="/static/index/css/main.css">
    <script src="/static/layui/layui.js?4"></script>
    <script src="/static/common/js/index.js"></script>
    <title>我的日记</title>
    <style>
        body {
            font-family: 'Comic Neue', cursive;
            background-size: cover;
            background-attachment: fixed;
            margin: 0;
            padding: 0;
            /* 使用 CSS 变量 */
            color: var(--base-font-color);
            background-color: var(--background-color);
        }

        .header {
            text-align: center;
            /* 使用相对单位，增强响应式 */
            padding: clamp(15px, 3vw, 30px); 
            /* 使用 CSS 变量 */
            background-color: var(--primary-color); 
            color: var(--primary-btn-color);
            box-shadow: 0 2px 5px var(--shadow-color);
            text-shadow: 2px 2px 4px var(--shadow-color);
            border-radius: 0 0 20px 20px; /* 圆角效果 */
            /* 添加过渡效果，提升交互体验 */
            transition: all 0.3s ease; 
            /* 提升可访问性，设置鼠标指针样式 */
            cursor: default; 
            /* 防止内容溢出 */
            overflow: hidden; 
        }

        /* 当鼠标悬停在 .header 上时，改变阴影和背景颜色 */
        .header:hover {
            box-shadow: 0 4px 10px var(--shadow-color);
            background-color: var(--primary-hover-color);
        }

        /* 针对小屏幕设备调整样式 */
        @media (max-width: 768px) {
            .header {
                padding: 15px;
                border-radius: 0;
            }
        }

        .container {
            display: flex;
            flex-direction: row;
            gap: 20px;
            padding: 20px;
            flex-wrap: wrap; /* 响应式布局 */
            justify-content: center;
            width: unset;
        }

        .calendar {
            flex: 1;
            max-width: 300px;
            background: var(--background-color);
            /* 使用 CSS 变量 */
            border: 2px solid var(--primary-color); 
            border-radius: 15px;
            padding: 15px;
            box-shadow: 5px 5px 10px var(--shadow-color);
        }

        .calendar-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            /* 使用 CSS 变量 */
            color: var(--primary-color); 
        }

        .calendar-header button {
            /* 使用 CSS 变量 */
            background-color: var(--primary-color); 
            color: var(--primary-btn-color);
            border: none;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            cursor: pointer;
            transition: opacity 0.3s;
        }

        .calendar-header button:hover {
            opacity: 0.8;
        }

        .calendar-grid {
            display: grid;
            grid-template-columns: repeat(7, 1fr);
            gap: 5px;
        }

        .calendar-day {
            text-align: center;
            padding: 10px;
            border-radius: 50%; /* 圆形日期 */
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .calendar-day:hover {
            /* 使用 CSS 变量 */
            background-color: var(--light-background-color); 
        }


        .calendar-day.has-entry {
            font-weight: bold;
            /* 使用 CSS 变量 */
            background-color: var(--primary-color); 
            color: var(--primary-btn-color);
        }

        .calendar-day.today {
            /* 使用 CSS 变量 */
            background-color: var(--secondary-color); 
            color: var(--primary-btn-color);
        }


        .diary {
            flex: 2;
            min-width: 300px;
            background: var(--background-color);
            /* 使用 CSS 变量 */
            border: 2px solid var(--primary-color); 
            border-radius: 15px;
            padding: 20px;
            box-shadow: 5px 5px 10px var(--shadow-color);
        }

        .diary-entry {
            margin-bottom: 20px;
            padding: 15px;
            /* 使用 CSS 变量 */
            background: var(--light-background-color); 
            border-left: 5px solid var(--primary-color);
            border-radius: 5px;
        }

        .diary-entry p {
            font-size: 16px;
            line-height: 1.6;
            /* 使用 CSS 变量 */
            color: var(--base-font-color); 
        }

        .diary-entry .time {
            font-size: 12px;
            /* 使用 CSS 变量 */
            color: var(--secondary-color); 
            float: right;
        }

        .calendar-day.selected {
            /* 使用 CSS 变量 */
            border: 2px solid var(--primary-hover-color); 
        }

        .calendar-day.first-day-with-entry {
            /* 使用 CSS 变量 */
            background-color: var(--primary-hover-color); 
            color: var(--primary-btn-color);
        }
        .massageImg img {
            max-width: 70%;
            max-height: 50%;
        }
    </style>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 从 localStorage 中读取保存的主题
            var selectedTheme = localStorage.getItem('selectedTheme');
            if (selectedTheme) {
                if (selectedTheme === 'default') {
                    document.documentElement.className = '';
                } else {
                    document.documentElement.className = selectedTheme;
                }
                var header = document.getElementById('header');
                if (header) {
                    if (selectedTheme === 'default') {
                        header.className = '';
                    } else {
                        header.className = selectedTheme;
                    }
                }
            }
        });
    </script>
</head>

<body>
    <div class="header">
        <h1>我的日记</h1>
    </div>
    <div class="container">
        <div class="calendar" id="calendar">
            <div class="calendar-header">
                <button id="prev-month">&lt;</button>
                <span id="calendar-title"></span>
                <button id="next-month">&gt;</button>
            </div>
            <div class="calendar-grid" id="calendar-grid"></div>
        </div>
        <div class="diary" id="diary">
            <h2 id="diary-date">请选择日期</h2>
            <div id="diary-entries"></div>
        </div>
    </div>

    <script>
        class DiaryApp {
            constructor() {
                this.currentDate = new Date();
                this.datesWithEntries = [];
                this.currentViewDate = null;
                this.init();
            }

            async init() {
                await this.fetchDiaryDates();
                const firstDayWithEntry = this.findFirstDayWithEntry();
                if (firstDayWithEntry) {
                    await this.loadDiary(firstDayWithEntry);
                }
                this.renderCalendar();
                this.setupEventListeners();
            }

            async fetchDiaryDates() {
                const year = this.currentDate.getFullYear();
                const month = String(this.currentDate.getMonth() + 1).padStart(2, '0');
                const monthParam = `${year}-${month}`;
                const url = `/tools/media/getDiaryDates?month=${monthParam}`;

                try {
                    const response = await fetch(url);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();
                    if (data.status === 1) {
                        this.datesWithEntries = data.data.map(item => item.date);
                        this.datesWithEntries.sort();
                    } else {
                        alert('接口返回状态非 1，未获取到有效日期数据');
                    }
                } catch (error) {
                    alert('获取日期失败，请稍后重试');
                }
            }

            findFirstDayWithEntry() {
                const year = this.currentDate.getFullYear();
                const month = this.currentDate.getMonth() + 1;
                const firstDay = new Date(year, month - 1, 1);
                const lastDay = new Date(year, month, 0);

                for (let day = 1; day <= lastDay.getDate(); day++) {
                    const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                    if (this.datesWithEntries.includes(dateStr)) {
                        return dateStr;
                    }
                }
                return null;
            }

            // 提取生成日期字符串的方法，提高代码复用性
            generateDateStr(year, month, day) {
                return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            }

            /**
             * 查找上一个月最后一个有日记条目的日期
             * @returns {string|null} 上一个月最后有日记条目的日期字符串，若没有则返回 null
             */
            findLastDayWithEntryInPrevMonth() {
                try {
                    // 创建一个新的日期对象，设置为当前日期的上一个月
                    const prevMonthDate = new Date(this.currentDate);
                    prevMonthDate.setMonth(prevMonthDate.getMonth());
                    const year = prevMonthDate.getFullYear();
                    const month = prevMonthDate.getMonth() + 1;
                    // 获取上一个月的最后一天
                    const lastDay = new Date(year, month, 0);

                    // 从最后一天开始向前遍历，查找有日记条目的日期
                    for (let day = lastDay.getDate(); day > 0; day--) {
                        const dateStr = this.generateDateStr(year, month, day);
                        if (this.datesWithEntries.includes(dateStr)) {
                            return dateStr;
                        }
                    }
                    return null;
                } catch (error) {
                    // 打印错误日志，方便调试
                    console.error('查找上一月最后有日记条目的日期时出错:', error);
                    return null;
                }
            }

            renderCalendar() {
                const year = this.currentDate.getFullYear();
                const month = this.currentDate.getMonth() + 1;
                const firstDay = new Date(year, month - 1, 1);
                const lastDay = new Date(year, month, 0);

                const calendarGrid = document.getElementById('calendar-grid');
                calendarGrid.innerHTML = '';

                document.getElementById('calendar-title').textContent = `${year}年${month}月`;

                for (let i = 0; i < firstDay.getDay(); i++) {
                    calendarGrid.appendChild(this.createDayElement('', true));
                }

                for (let day = 1; day <= lastDay.getDate(); day++) {
                    const dateStr = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
                    const isToday = new Date().toDateString() === new Date(year, month - 1, day).toDateString();
                    const hasEntry = this.datesWithEntries.includes(dateStr);
                    const isSelected = dateStr === this.currentViewDate;
                    calendarGrid.appendChild(this.createDayElement(day, false, isToday, hasEntry, dateStr, isSelected));
                }
            }

            createDayElement(day, isPlaceholder, isToday = false, hasEntry = false, dateStr = '', isSelected = false) {
                const dayElement = document.createElement('div');
                dayElement.className = 'calendar-day';
                if (isPlaceholder) {
                    dayElement.style.visibility = 'hidden';
                } else {
                    dayElement.textContent = day;
                    if (isToday) dayElement.classList.add('today');
                    if (hasEntry) dayElement.classList.add('has-entry');
                    if (isSelected) dayElement.classList.add('selected');
                    dayElement.addEventListener('click', () => this.loadDiary(dateStr));
                }
                return dayElement;
            }

            async loadDiary(dateStr) {
                const previousSelected = document.querySelector('.calendar-day.selected');
                if (previousSelected) {
                    previousSelected.classList.remove('selected');
                }

                const url = `/tools/media/getDiaryList?date=${dateStr}`;
                try {
                    const response = await fetch(url);
                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }
                    const data = await response.json();
                    const diaryEntries = document.getElementById('diary-entries');
                    const diaryDate = document.getElementById('diary-date');
                    diaryEntries.innerHTML = '';
                    diaryDate.textContent = dateStr;
                    this.currentViewDate = dateStr;

                    if (data.status === 1 && data.data.data.length > 0) {
                        data.data.data.forEach(entry => {
                            const entryElement = document.createElement('div');
                            entryElement.className = 'diary-entry';

                            let mediaStr = '';
                            if (entry.media) {
                                const mediaInfo = JSON.parse(entry.media_info);
                                if (mediaInfo.media_type === 'mp4' || mediaInfo.media_type === 'm3u8') {
                                    mediaStr = `<p class="massageImg clear showVideo${entry.id}" vid="${entry.media}"><video width="400px"  controls=""  name="media"><source src="${entry.media}" type="video/mp4"></video></p>`;
                                } else if (mediaInfo.media_type === 'mp3') {
                                    mediaStr = `<p class="massageImg clear"><audio id="music_${entry.id}" class="music" controls="controls" loop="loop" onplay="stopOther(this)" preload="none" controlsList="nodownload" οncοntextmenu="return false" name="media"><source src="${entry.media}" type="audio/mpeg"></audio></p>`;
                                } else {
                                    mediaStr = `<p  class="massageImg clear"><img class="massageImgCommon massageImg_${mediaInfo.media_type}"  onclick="showMessageImg(this)" src="${entry.media}"></p>`;
                                }
                            }

                            entryElement.innerHTML = `
                                <p>${entry.contents}</p>
                                ${mediaStr}
                                <p class="time">${new Date(entry.ctime * 1000).toLocaleTimeString()}</p>
                            `;
                            diaryEntries.appendChild(entryElement);
                        });
                    } else {
                        diaryEntries.innerHTML = '<p>没有日记内容</p>';
                    }

                    this.renderCalendar();
                } catch (error) {
                    alert('加载日记失败，请稍后重试');
                }
            }

            setupEventListeners() {
                document.getElementById('prev-month').addEventListener('click', async () => {
                    // 先更新当前日期为上一个月
                    this.currentDate.setMonth(this.currentDate.getMonth() - 1);
                    // 重新获取上一个月有日记条目的日期列表
                    await this.fetchDiaryDates();
                    // 查找上一个月最后有日记条目的日期
                    const lastDayWithEntry = this.findLastDayWithEntryInPrevMonth();
                    if (lastDayWithEntry) {
                        // 若找到，则加载对应的日记
                        await this.loadDiary(lastDayWithEntry);
                    } else {
                        // 若未找到，清空当前视图日期并重新渲染日历
                        this.currentViewDate = null;
                        this.renderCalendar();
                    }
                });

                document.getElementById('next-month').addEventListener('click', async () => {
                    this.currentDate.setMonth(this.currentDate.getMonth() + 1);
                    await this.fetchDiaryDates();
                    const firstDayWithEntry = this.findFirstDayWithEntry();
                    if (firstDayWithEntry) {
                        await this.loadDiary(firstDayWithEntry);
                    } else {
                        this.currentViewDate = null;
                        this.renderCalendar();
                    }
                });
            }
        }

        document.addEventListener('DOMContentLoaded', () => {
            new DiaryApp();
        });
    </script>
</body>

</html>